var User = require('../Models/User');
var _ = require('lodash');
var validator = require('validator');
const globalResponseCode = require('../base/ResponseCode');
var logTool = require('../Tools/LogTool');

var { request, summary, body, description, tags } = require('koa-swagger-decorator');
var userSchema = {
	userName: { type: 'string', required: true, example: 'zzz' },
	realName: { type: 'string', required: true, example: '张三' },
	password: { type: 'string', required: true, example: '123456' },
	roleId: { type: 'number', require: false, example: 1 },
	mobile: { type: 'string', require: false, example: '13332455612' },
	email: { type: 'string', require: false, example: 'asf@mail.com' }
}

var userResponseCode = {
	ADD_FAIL: { code: 20001, message: '添加用户失败！' },
	REGISTER_FAIL: { code: 20002, message: '删除用户失败！' },
	UPDATE_FAIL: { code: 20003, message: '修改用户失败！' },
	DELETE_FAIL: { code: 20004, message: '删除用户失败！' },
	USER_NOT_EXIST: { code: 20005, message: '用户不存在！' },
	USER_EXIST: { code: 20006, message: '用户已存在!' },
	PASSWORD_ERROR: { code: 20007, message: '用户密码错误!' },
};


class UserController {

	@tags(['User'])
	@request('post', '/user/register')
	@summary('注册')
	@body(userSchema)
	@description('用户注册 默认角色为测试， 1:产品, 2:开发, 3:测试, 4:管理员')
	async register(ctx) {
		try {
			let user = ctx.request.body;
		//	console.log('user1',user)
			if (!user.userName || !user.realName || !user.password) {
				return ctx.body = globalResponseCode.PARAMS_ERROR;
			}
			if (_.isUndefined(user.userName) || _.isUndefined(user.realName) || _.isUndefined(user.password)) {
				return ctx.body = globalResponseCode.PARAMS_ERROR;
			}
			let result = await User.insert(user);

			if (result == 0) {
				return ctx.body = userResponseCode.ADD_FAIL;
			} else {
				let user = await User.query({ id: result });
				delete user.password;
				ctx.session.user = user[0];
				// console.log('ctx.session.user',ctx.session, ctx.session.user)
				// console.log('merge',_.merge({}, globalResponseCode.SUCCESS, { data: user[0] }))
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, { data: user[0] });
			}
		} catch (error) {
			if (error.errno == 1062) {
				return ctx.body = userResponseCode.USER_EXIST;
			}
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['User'])
	@request('post', '/user/add')
	@summary('添加用户')
	@body(userSchema)
	@description('只能管理员可以添加用户，添加用户的默认角色为测试，4:管理员, 1:产品, 2:开发, 3:测试')
	async addUser(ctx) {
		try {
			if (ctx.session.user) {
				if (ctx.session.user.roleId !== 4) {
					return ctx.body = globalResponseCode.NO_AUTH;
				}
				let user = ctx.request.body;

				if (!user.userName || !user.realName || !user.password) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (_.isUndefined(user.userName) || _.isUndefined(user.realName) || _.isUndefined(user.password)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (user.mobile && !validator.isMobilePhone(user.mobile)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (user.email && !validator.isEmail(user.email)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				let result = await User.insert(user);
				if (result == 0) {
					return ctx.body = userResponseCode.ADD_FAIL;
				} else {
					return ctx.body = _.merge({}, globalResponseCode.SUCCESS, { data: { userId: result } });
				}
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			if (error.errno == 1062) {
				return ctx.body = userResponseCode.USER_EXIST;
			}
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['User'])
	@request('post', '/user/login')
	@summary('登录')
	@body({
		userName: { type: 'string', required: true, example: 'admin' },
		password: { type: 'string', required: true, example: 'admin' }
	})
	async login(ctx) {
		try {
			let condition = ctx.request.body;
			if (!condition.userName || _.isUndefined(condition.userName)) {
				return ctx.body = globalResponseCode.PARAMS_ERROR;
			}
			if (!condition.password || _.isUndefined(condition.password)) {
				return ctx.body = globalResponseCode.PARAMS_ERROR;
			}
			let user = await User.queryByUserName(condition.userName);

			if (_.isEmpty(user)) {
				return ctx.body = userResponseCode.USER_NOT_EXIST;
			}
			if (condition.password !== user.password) {
				return ctx.body = userResponseCode.PASSWORD_ERROR;
			} else {
				delete user.password;
				ctx.session.user = user;
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, { data: user });
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['User'])
	@request('post', '/user/list')
	@summary('获取所有用户')
	@body({
		page: { type: 'int', required: true, example: 1 },
		size: { type: 'int', required: true, example: 10 },
		roleId: { type: 'int', required: false, example: 1 },
		id: { type: 'int', require: false, example: 2 },
		userName: { type: 'string', require: false, example: 'a' },
		realName: { type: 'string', require: false, example: 'a' },
	})
	async getUserList(ctx) {
		try {
			if (ctx.session.user) {
				let condition = ctx.request.body;
				if (!condition.page || !condition.size
					|| !_.isInteger(condition.page) || !_.isInteger(condition.size)
					|| condition.page < 1 && condition.size < 1) {
					return ctx.body = globalResponseCode.PAGE_PARAMS_ERROR;
				}

				if (condition.id && !_.isInteger(condition.id)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (condition.userName && _.isUndefined(condition.userName)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (condition.realName && _.isUndefined(condition.realName)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				let users = await User.pageList(condition);
				delete condition.page;
				delete condition.size;
				let count = await User.count(condition);
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, { data: { userList: users, count: count } });
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['User'])
	@request('post', '/user/query')
	@summary('查询用户')
	@body({
		roleId: { type: 'int', required: false, example: 1 },
		id: { type: 'int', require: false, example: 2 },
		userName: { type: 'string', require: false, example: 'a' },
		realName: { type: 'string', require: false, example: 'a' },
	})
	async queryUsers(ctx) {
		try {
			if (ctx.session.user) {
				let condition = ctx.request.body;
				if (condition.id && !_.isInteger(condition.id)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (condition.userName && _.isUndefined(condition.userName)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (condition.realName && _.isUndefined(condition.realName)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				if (condition.roleId && !_.isInteger(condition.roleId)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				let users = await User.query(ctx.request.body);
				
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, { data: users });
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['User'])
	@request('post', '/user/update')
	@summary('修改用户')
	@description('只有管理员和自己可以修改')
	@body({
		id: { type: 'int', required: true, example: 2 },
		roleId: { type: 'int', require: false, example: 1 },
		mobile: { type: 'string', require: false, example: '13332455612' },
		email: { type: 'string', require: false, example: 'asf@mail.com' },
		password: { type: 'string', require: false, example: '123456' },
	})
	async updateUser(ctx) {
		try {
			if (ctx.session.user) {
				if (ctx.session.user.roleId == 4 || (ctx.session.user.id == ctx.request.body.id)) {
					let user = ctx.request.body;
					if (!user.id || !_.isInteger(user.id) || _.keys(user).length <= 1) {
						return ctx.body = globalResponseCode.PARAMS_ERROR;
					}
					if(_.keys(user).length == 1){
						return ctx.body = globalResponseCode.PARAMS_ERROR;
					}
					if (user.mobile && !validator.isMobilePhone(user.mobile)) {
						return ctx.body = globalResponseCode.PARAMS_ERROR;
					}
					if (user.email && !validator.isEmail(user.email)) {
						return ctx.body =globalResponseCode.PARAMS_ERROR;
					}
					let result = await User.update(ctx.request.body);
					if (result) {
						return ctx.body = globalResponseCode.SUCCESS;
					} else {
						return ctx.body = userResponseCode.UPDATE_FAIL;
					}
				} else {
					return ctx.body = globalResponseCode.NO_AUTH;
				}
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['User'])
	@request('post', '/user/logout')
	@summary('注销')
	async logout(ctx) {
		if (ctx.session.user) {
			delete ctx.session.user;
			return ctx.body = globalResponseCode.SUCCESS;
		} else {
			return ctx.body = globalResponseCode.NO_LOGIN;
		}
	}

	@tags(['User'])
	@request('get', '/currentUser')
	@summary('获取当前用户')
	async getCurrentUser(ctx){
		try {
			if(ctx.session.user){
				return ctx.body = _.merge({}, globalResponseCode.SUCCESS, {data:ctx.session.user});
			}else{
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['User'])
	@request('delete', '/user/delete')
	@summary('删除用户')
	@description('只有管理员可以删除用户')
	@body(
		{ id: { type: 'int', required: true, example: 2 } }
	)
	async deleteUser(ctx) {
		try {
			if (ctx.session.user) {
				if (ctx.session.user.roleId !== 4) {
					return ctx.body = globalResponseCode.NO_AUTH;
				}
				if (!ctx.request.body.id || !_.isInteger(ctx.request.body.id)) {
					return ctx.body = globalResponseCode.PARAMS_ERROR;
				}
				let result = false;
				try {
					result = await User.deleteById(ctx.request.body.id);
					if (result) {
						return ctx.body = globalResponseCode.SUCCESS;
					}else{
						return ctx.body = userResponseCode.DELETE_FAIL;
					}
				} catch (error) {
					return ctx.body = globalResponseCode.DB_ERROR;
				}
			} else {
				return ctx.body = globalResponseCode.NO_LOGIN;
			}
		} catch (error) {
			logTool.logError(ctx, error);
			return ctx.body = globalResponseCode.SYSTEM_EXCEPTION;
		}
	}

	@tags(['workbanch'])
	@request('get', '/workbanch/dynamiclogs')
	@summary('获取当前用户所有操作')

	async getDynamiclogs(ctx){

			let result =await User.getDynamiclogTableSql()

			return ctx.body= _.merge({}, globalResponseCode.SUCCESS, {data:result});
		


		}


	

}

module.exports = new UserController()

